<template>
  <div class="m-school-basic-info">
    <div class="m-h3-btn-box border">
      <h3>基本信息</h3>
      <div class="u-btn-box">
        <el-button type="primary" @click="baseInformationSave()" size="small">{{
          isBaseInformationSave ? '保存' : '编辑'
        }}</el-button>
      </div>
    </div>
    <el-form
      :model="baseInformation"
      label-width="120px"
      label-position="left"
      :rules="baseRules"
      ref="baseInformation"
    >
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label>
            <el-upload
              class="avatar-uploader"
              :action="url"
              :show-file-list="false"
              :http-request="uploadImg"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="baseInformation.schoolImageUrl"
                :src="baseInformation.schoolImageUrl"
                class="avatar"
              />
              <span
                class="el-upload-list__item-delete"
                @click.stop="handleAvatarRemove()"
                v-if="baseInformation.schoolImageUrl"
                >x</span
              >
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="学校名称：" prop="schoolName">
                <el-input
                  v-model="baseInformation.schoolName"
                  clearable
                  :disabled="!isBaseInformationSave"
                  placeholder="请输入学校姓名"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="所属地区：" prop="region">
                <el-cascader
                  v-if="$store.state.common.regions[0]"
                  v-model="baseInformation.region"
                  :options="$store.state.common.regions"
                  placeholder="请选择所属地区"
                  clearable
                  :disabled="!isBaseInformationSave"
                ></el-cascader>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="学校性质：" prop="schoolType">
                <nice-select
                  v-model="baseInformation.schoolType"
                  placeholder="请选择学校性质"
                  clearable
                  :options="selectEnums.schoolType"
                  labelkey="name"
                  :disabled="!isBaseInformationSave"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="覆盖年级：" prop="coverageGrade">
                <nice-select
                  v-model="baseInformation.coverageGrade"
                  placeholder="请选择覆盖年级"
                  clearable
                  :multiple="true"
                  :disabled="!isBaseInformationSave"
                  :options="selectEnums.coverageGrade"
                ></nice-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="学生规模：" prop="studentScale">
                <nice-select
                  v-model="baseInformation.studentScale"
                  placeholder="请选择学生规模"
                  clearable
                  :options="selectEnums.studentScale"
                  :disabled="!isBaseInformationSave"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="教师规模：" prop="teacherScale">
                <nice-select
                  v-model="baseInformation.teacherScale"
                  filterable
                  placeholder="请选择教师规模"
                  clearable
                  :disabled="!isBaseInformationSave"
                  :options="selectEnums.teacherScale"
                  labelkey="name"
                  valuekey="id"
                ></nice-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="学校等级：" prop="level">
                <nice-select
                  v-model="baseInformation.level"
                  filterable
                  placeholder="请选择学校等级"
                  clearable
                  :disabled="!isBaseInformationSave"
                  :options="selectEnums.level"
                ></nice-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11">
              <el-form-item label="校训：" prop="schoolMotto">
                <el-input
                  type="textarea"
                  maxlength="200"
                  v-model="baseInformation.schoolMotto"
                  placeholder="请输入校训"
                  clearable
                  :disabled="!isBaseInformationSave"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="40">
            <el-col :span="11"> 人脸采集链接：http//fhafalfdlafhaskfla </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import { ossUpload } from '@/api/api.js'
import { editSchool } from '@/api/user.js'
import { adminschoolupdate } from '@/api/user'
export default {
  props: {
    url: {
      type: String,
      default: ''
    },
    selectEnums: {
      type: [Object, Array],
      default: function () {
        return []
      }
    },
    basicInfo: {
      type: Object,
      default: function () {
        return {}
      }
    },
    schoolId: ''
  },
  watch: {
    basicInfo (val, oldval) {
      this.$refs['baseInformation'].clearValidate()
      this.isBaseInformationSave = false
      this.baseInformation = JSON.parse(JSON.stringify(val))
      this.baseInformation.schoolImageUrl = val.schoolImageUrl || ''
      this.baseInformation.schoolName = val.schoolName
      this.baseInformation.schoolType = val.schoolType
      this.baseInformation.region = this.$deepcopy(val.region) || []
      this.baseInformation.coverageGrade =
        this.$deepcopy(val.coverageGrade) || []
      this.baseInformation.studentScale = val.studentScale
      this.baseInformation.teacherScale = val.teacherScale
      this.baseInformation.schoolMott = val.schoolMott
      this.baseInformation.level = val.level
      this.baseInformation.online_number = val.online_number
      this.baseInformation.market_id = val.market_id
      this.baseInformation.recruit_students_pattern =
        val.recruit_students_pattern
      this.baseInformation.school_agents = val.school_agents
      this.userFilter(val.market_id)
    }
  },
  data () {
    return {
      baseInformation: {
        schoolImageUrl: '',
        schoolName: '',
        schoolType: '',
        region: [],
        coverageGrade: [],
        studentScale: '',
        teacherScale: '',
        level: '',
        schoolMott: ''
      },
      isBaseInformationSave: false,
      userList: [],
      baseRules: {
        schoolName: [
          { required: true, message: '请输入学校名称', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择所属地区', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    // 更换选中的值
    changeData (e, key) {
      this.$set(this.baseInformation, key, e)
      this.userFilter('')
    },
    // 下拉选项过多时过滤
    userFilter (query = '') {
      if (this.selectEnums.market_id) {
        if (this.selectEnums.market_id.length > 50) {
          this.userList = this.selectEnums.market_id.slice(0, 50)
        } else {
          this.userList = this.selectEnums.market_id
        }
      }
    },
    baseInformationSave () {
      if (this.isBaseInformationSave) {
        this.$refs['baseInformation'].validate(valid => {
          if (valid) {
            if (
              this.baseInformation.coverageGrade &&
              this.baseInformation.coverageGrade.length
            ) {
              this.getInit()
            } else {
              this.baseInformationSubmit('0', '0', '0', '0')
            }
          }
        })
      } else {
        this.isBaseInformationSave = true
      }
    },
    getInit () {
      let nurseryGrade = 0,
        juniorGrade = 0,
        middleGrade = 0,
        highGrade = 0
      this.selectEnums.coverageGrade.forEach(item => {
        this.baseInformation.coverageGrade.forEach(ele => {
          if (ele === item.value) {
            if (item.label === '幼儿园') {
              nurseryGrade = 1
            } else if (item.label === '小学') {
              juniorGrade = 1
            } else if (item.label === '初中') {
              middleGrade = 1
            } else if (item.label === '高中') {
              highGrade = 1
            }
          }
        })
      })
      this.baseInformationSubmit(
        nurseryGrade,
        juniorGrade,
        middleGrade,
        highGrade
      )
    },
    async baseInformationSubmit (
      nurseryGrade,
      juniorGrade,
      middleGrade,
      highGrade
    ) {
      let regions = this.$filterRegion(
        {
          province: this.baseInformation.region[0],
          city: this.baseInformation.region[1],
          area: this.baseInformation.region[2]
        },
        this.$store.state.common.regions
      )
      let res = await adminschoolupdate({
        ...this.baseInformation,
        coverageGrade: 0,
        address: '',
        area: this.baseInformation.region[2],
        areaName: regions[2],
        city: this.baseInformation.region[1],
        cityName: regions[1],
        province: this.baseInformation.region[0],
        provinceName: regions[0],
        highGrade: highGrade,
        juniorGrade: juniorGrade,
        level: this.baseInformation.level,
        middleGrade: middleGrade,
        nurseryGrade: nurseryGrade,
        openStatus: 1,
        schoolMaster: this.baseInformation.schoolMaster,
        schoolName: this.baseInformation.schoolName,
        schoolType: this.baseInformation.schoolType,
        studentScale: this.baseInformation.studentScale,
        teacherScale: this.baseInformation.teacherScale
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.isBaseInformationSave = false
        this.$message.success('编辑成功')
        this.$emit('refreshData')
      } else {
        this.$message.error(data.msg)
        this.isBaseInformationSave = true
      }
    },
    async uploadImg (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await ossUpload(formData, 'SCHOOL_COVER')
      if (res[0]) {
        return
      }
      this.baseInformation.schoolImageUrl = res[1].data.url
      console.log(this.baseInformation)
    },
    beforeAvatarUpload (file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式或 GIF 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleAvatarRemove () {
      this.baseInformation.schoolImageUrl = ''
    }
  }
}
</script>
<style scoped></style>
